package com.ltcode.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.img.ImgUtil;
import dev.langchain4j.data.message.ImageContent;
import dev.langchain4j.data.message.TextContent;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import jakarta.annotation.Resource;
import jakarta.websocket.server.PathParam;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;

/**
 * @Author： ltcode
 * @Create by： 2025/8/11 0011 21:27
 * @ClassName: ChatMultimodalityDemoController
 * @Describe：多模态聊天模型
 */
@RestController
@RequestMapping("/multi")
public class ChatMultimodalityDemoController {
    @Resource(name = "qwenImage")
    private ChatModel chatModel;
    @Resource(name = "streamQwenImage")
    private StreamingChatModel streamingChatModel;
    SseEmitter sseEmitter;
    @PostMapping("/img2text")
    public String img2text(@RequestParam("msg") String msg, @RequestParam("file") MultipartFile file) throws IOException {
        String base64 = Base64.encode(file.getBytes());
        UserMessage userMessage = UserMessage.from(TextContent.from(msg), ImageContent.from(base64, "image/jpeg"));
        ChatResponse chat = chatModel.chat(userMessage);
        return chat.aiMessage().text();
    }

    @PostMapping("/img2text2")
    public Mono<String> img2text2(@RequestParam("msg") String msg, @RequestParam("file") MultipartFile file) throws IOException {
        String base64 = Base64.encode(file.getBytes());
        UserMessage userMessage = UserMessage.from(TextContent.from(msg), ImageContent.from(base64, "image/jpeg"));
        ChatRequest chatRequest = ChatRequest.builder().messages(userMessage).build();

         streamingChatModel.chat(chatRequest, new StreamingChatResponseHandler() {
            @SneakyThrows
            @Override
            public void onPartialResponse(String partialResponse) {
                System.out.println("partialResponse: " + partialResponse);
                Mono.justOrEmpty(partialResponse);
            }

            @Override
            public void onCompleteResponse(ChatResponse completeResponse) {
                System.out.println("completeResponse: " + completeResponse);
            }

            @Override
            public void onError(Throwable error) {
                System.out.println("error: " + error);
            }
        });
        return Mono.justOrEmpty("{}");
    }
}
